﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class 数据算法_AES加解密Encode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// 提交数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        //创建一个加密key
        string guid = Guid.NewGuid().ToString().Replace("-", "");
        byte[] ByteKey = System.Text.UTF8Encoding.UTF8.GetBytes(guid.ToCharArray());
        System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged();
        var encode = Aes.CreateEncryptor(ByteKey, ByteKey.Take(16).ToArray());


        byte[] byteArray = new byte[FileUpload1.PostedFile.InputStream.Length];
        FileUpload1.PostedFile.InputStream.Read(byteArray, 0, byteArray.Length);


        ///加密
        var list = encode.TransformFinalBlock(byteArray, 0, byteArray.Length).ToList();

        //写入加密KEY
        for (int i = 31; i >= 0; i--)
        {
            //加入到集合
            list.Insert(0, ByteKey[i]);
        }

        Response.Write(guid);

        //转换成Array
        byteArray = list.ToArray();



        System.IO.File.WriteAllBytes(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Encode", byteArray);


        Response.Write("<br/>" + System.Text.UTF8Encoding.UTF8.GetString(byteArray.Take(32).ToArray()));
    }

    /// <summary>
    /// 解密数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {

        //写新解密文
        using (System.IO.FileStream writeFile = System.IO.File.Create(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Dencode"))
        {

            //读取加密码key
            using (System.IO.Stream sr = FileUpload2.PostedFile.InputStream)
            {

                System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged();
                byte[] ByteKey = new byte[32];
                sr.Read(ByteKey, 0, ByteKey.Length);
                //读取KEY
                using (System.Security.Cryptography.ICryptoTransform dencode = Aes.CreateDecryptor(ByteKey, ByteKey.Take(16).ToArray()))
                {
                    //开始解密一次性
                    //byte[] result = dencode.TransformFinalBlock(reads, 0, len);
                    //使用DES流解密
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(writeFile, dencode, System.Security.Cryptography.CryptoStreamMode.Write))
                    {

                        while (sr.CanRead)
                        {

                            byte[] reads = new byte[2048];
                            //读取的有效长度
                            int len = sr.Read(reads, 0, reads.Length);
                            if (len == 0) { break; }
                            cs.Write(reads, 0, len);

                        }
                        cs.Close();
                    }

                }


                sr.Close();
            }


            writeFile.Close();
        }

    }
    /// <summary>
    /// 十六进制转换为字节数组
    /// </summary>
    /// <param name="hexString"></param>
    /// <returns></returns>
    public static byte[] ToBytes(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        var returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button3_Click(object sender, EventArgs e)
    {

        string guid = Guid.NewGuid().ToString().Replace("-", "");
        byte[] ByteKey = System.Text.UTF8Encoding.UTF8.GetBytes(guid.ToCharArray());
        //初始化向量
        byte[] iv = new byte[16];

        //加密10 万次
        //解密10 万次
        System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged();
        var encode = Aes.CreateEncryptor(iv, ByteKey.Take(16).ToArray());


        System.Security.Cryptography.ICryptoTransform dencode = Aes.CreateDecryptor(iv, ByteKey.Skip(0).Take(16).ToArray());

        string xxxx = "687200720068D13448FB02000C7C0800030526000601010012460400252500001000FF9C00004001140000000200160202123150230101114074052543037634000029000000000000051018800254F9B19397FB3616E8194146F0D05AB20B000100010001000B2C0101000100010001000BD809010001003C1601000B53010B4F010B34210BF41A0B30070BB8060BE803010101000100010001000100010001000100010001000100010001000100010001000100010001000B2C010B2C010101010001000100010001000B8C0AD4160B2C0101000100010001000B53000B52000B98089E1616010001000100010001000100010001000B771907E13AB8430BB4990B0001010101000101010001000100010001000100010001000100010001000100010001000B4C0401000100010001000100010001000B407407CDCCC4430733F3C74307CDECCA4501010BC8000100010101000B6C390B8025010001000B80250B08070B7D010B810101000100010001000BE8030BB0040BF41A0BE8030BF4010B84030100010001000100010001000B7F010B81010B7F010B80010B80010B81010B7F010B81010B7F010B81010B7F010B80010B7F010B81010B7F010B80010B80010B81010B7F010B80010B7F010B80010B7F010B7F010B7E010B7F010B80010B7F010B80010B80010B7F010B80010B7E010B80010B7E010B7F010B7F010B80010B7F010B81010B7F010B81010B7F010B81010B7F010B80010B7F010B7F010B7E010B7F010B7E010B7F010B7E010B7F010B7E010B7E010B80010B80010B81010B81010B7F010B80010B7F010B81010B7E010B80010B7E010B7E010B7D010B7F010B7D010B7F010B7D010B7E010B7D010B7E010B7D010B7F010B7D010B7D010B7F010B80010B7E010B7F010B7F010B80010B80010B80010B81010B80010B80010B80010B01010B1B000BCE000B1B000BA08F0B4C040B4C040B4C040B4C040BE8030BE8030BE8030BA08F0BE8030BB0040B4C040BE8030B4C040BE8030BE8030BA08F0BB0040BB0040BE8030BE8030BA08F0BA08F0BA08F1016";

        byte[] byteArray = ToBytes(xxxx);

        byte[] enc = null;
        Action abc = () =>
        {
            for (int i = 0; i < 10 * 10000; i++)
            {
                ///加密
                enc = encode.TransformFinalBlock(byteArray, 0, byteArray.Length);

            }
        };

        abc.StopwatchRun();
        byte[] ddd = null;
        Action abc1 = () =>
        {
            for (int i = 0; i < 10 * 10000; i++)
            {
                ///解密
                ddd = dencode.TransformFinalBlock(enc, 0, enc.Length);

            }
        };




        Response.Write(string.Format("<br/>加密10 万次{0},解密10 万次{1},原数据长度:{2},加密后长度:{3}", abc.StopwatchRun(), abc1.StopwatchRun(), xxxx.Length, enc.Length));
        Response.Write("<br/>" + BitConverter.ToString(ddd));

    }
    /// <summary>
    /// CBC模式10万次
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button4_Click(object sender, EventArgs e)
    {
        string guid = Guid.NewGuid().ToString().Replace("-", "");
        
        byte[] ByteKey = "2F 77 77 77 2E 69 6E 74 65 73 74 2E 63 6F 6D 2F".ToBytes();
        //初始化向量
        byte[] iv = "69 6E 74 65 73 74 40 69 6E 74 65 73 74 2E 63 6E".ToBytes();
        System.Security.Cryptography.RijndaelManaged Aes = new System.Security.Cryptography.RijndaelManaged()
        {
            //設定 cipher 格式 AES-256-CBC
            BlockSize = 128,
            KeySize = 128,
            FeedbackSize = 128,
            Padding = System.Security.Cryptography.PaddingMode.PKCS7,
            Mode = System.Security.Cryptography.CipherMode.CBC,
        };
        //加密10 万次
        //解密10 万次
        var encode = Aes.CreateEncryptor(ByteKey.Take(16).ToArray(), iv);


        System.Security.Cryptography.ICryptoTransform dencode = Aes.CreateDecryptor(ByteKey.Take(16).ToArray(), iv);

        string xxxx = "687200720068D13448FB02000C7C0800030526000601010012460400252500001000FF9C00004001140000000200160202123150230101114074052543037634000029000000000000051018800254F9B19397FB3616E8194146F0D05AB20B000100010001000B2C0101000100010001000BD809010001003C1601000B53010B4F010B34210BF41A0B30070BB8060BE803010101000100010001000100010001000100010001000100010001000100010001000100010001000B2C010B2C010101010001000100010001000B8C0AD4160B2C0101000100010001000B53000B52000B98089E1616010001000100010001000100010001000B771907E13AB8430BB4990B0001010101000101010001000100010001000100010001000100010001000100010001000B4C0401000100010001000100010001000B407407CDCCC4430733F3C74307CDECCA4501010BC8000100010101000B6C390B8025010001000B80250B08070B7D010B810101000100010001000BE8030BB0040BF41A0BE8030BF4010B84030100010001000100010001000B7F010B81010B7F010B80010B80010B81010B7F010B81010B7F010B81010B7F010B80010B7F010B81010B7F010B80010B80010B81010B7F010B80010B7F010B80010B7F010B7F010B7E010B7F010B80010B7F010B80010B80010B7F010B80010B7E010B80010B7E010B7F010B7F010B80010B7F010B81010B7F010B81010B7F010B81010B7F010B80010B7F010B7F010B7E010B7F010B7E010B7F010B7E010B7F010B7E010B7E010B80010B80010B81010B81010B7F010B80010B7F010B81010B7E010B80010B7E010B7E010B7D010B7F010B7D010B7F010B7D010B7E010B7D010B7E010B7D010B7F010B7D010B7D010B7F010B80010B7E010B7F010B7F010B80010B80010B80010B81010B80010B80010B80010B01010B1B000BCE000B1B000BA08F0B4C040B4C040B4C040B4C040BE8030BE8030BE8030BA08F0BE8030BB0040B4C040BE8030B4C040BE8030BE8030BA08F0BB0040BB0040BE8030BE8030BA08F0BA08F0BA08F1016";

        byte[] byteArray = ToBytes(xxxx);

        byte[] enc = null;
        Action abc = () =>
        {
            for (int i = 0; i < 10 * 10000; i++)
            {
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encode, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(byteArray, 0, byteArray.Length);
                    }
                    enc = msEncrypt.ToArray();
                }

                //enc = encode.TransformFinalBlock(byteArray, 0, byteArray.Length);

            }
        };

        abc.StopwatchRun();
        byte[] ddd = null;
        Action abc1 = () =>
        {
            for (int i = 0; i < 10 * 10000; i++)
            {
                ///解密
                ddd = dencode.TransformFinalBlock(enc, 0, enc.Length);

            }
        };




        Response.Write(string.Format("<br/>加密10 万次{0},解密10 万次{1},原数据长度:{2},加密后长度:{3}", abc.StopwatchRun(), abc1.StopwatchRun(), byteArray.Length, enc.Length));
        Response.Write("<br/>" + BitConverter.ToString(ddd));


    }
}



//程式碼如下，將字串 "text to be encrypted" 加密後解密看結果是否相同 : 
public class Encrypt
{
    System.Security.Cryptography.RijndaelManaged rijalg = new System.Security.Cryptography.RijndaelManaged();

    void Awake()
    {
        //-----------------
        //設定 cipher 格式 AES-256-CBC
        rijalg.BlockSize = 128;
        rijalg.KeySize = 128;
        rijalg.FeedbackSize = 128;
        rijalg.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
        rijalg.Mode = System.Security.Cryptography.CipherMode.CBC;

        rijalg.Key = System.Text.Encoding.ASCII.GetBytes("IHazSekretKey");
        rijalg.IV = System.Text.Encoding.ASCII.GetBytes("1234567890123456");

        //-----------------
        //加密
        System.Security.Cryptography.ICryptoTransform encryptor = rijalg.CreateEncryptor(rijalg.Key, rijalg.IV);

        byte[] encrypted;
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write("text to be enccrypted");
                }
                encrypted = msEncrypt.ToArray();
            }
        }



        //-----------------
        //解密
        System.Security.Cryptography.ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);

        string plaintext;
        // Create the streams used for decryption. 
        using (MemoryStream msDecrypt = new MemoryStream(encrypted))
        {
            using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {

                    // Read the decrypted bytes from the decrypting stream 
                    // and place them in a string.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }


    }
}



